
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7 .mark{
 8     position:absolute;
 9     height:100px;
10     width:100px;
11     left:100px;
12     top:180px;
13     border:1px solid #000;
14     cursor:move;
15 }
16     </style>
17 </head>
18 <body>
19 <canvas id="c1"></canvas> //显示原图像
20 <div class="mark" id="mark"></div>
21 <canvas id="c3"></canvas> //显示剪切后的图像
22 <script>
23     let canvas1 = document.getElementById("c1")
24     let oMark = document.getElementById("mark")
25     let canvas3= document.getElementById("c3")
26     canvas1.height = 300;
27     canvas1.width=300;
28     canvas3.height=100;
29     canvas3.width=100;
30     var cxt1 = canvas1.getContext("2d")
31     var img = new Image();
32     img.src = "./image/image_01.jpg";
33     var srcX = oMark.offsetLeft-canvas1.getBoundingClientRect().left;
34     var srcY = oMark.offsetTop-canvas1.getBoundingClientRect().top;
35     var sWidth = oMark.offsetWidth;
36     var sHeight = oMark.offsetHeight;
37 
38     var canvas2 = document.createElement("canvas")
39     var cxt2=canvas2.getContext("2d")
40     img.onload = function(){
41         cxt1.drawImage(img,0,0,canvas1.width,canvas1.height);
42         var dataImg = cxt1.getImageData(srcX,srcY,sWidth,sHeight)
43         canvas2.width = sWidth;
44         canvas2.height = sHeight;
45         cxt2.putImageData(dataImg,0,0,0,0,canvas2.width,canvas2.height)
46         var img2 = canvas2.toDataURL("image/png");
47 
48         var cxt3=canvas3.getContext("2d")
49         var img3 = new Image();
50         img3.src = img2;
51         img3.onload  = function(){
52             cxt3.drawImage(img3,0,0,canvas3.width,canvas3.height)
53         }
54     }
55 </script>
56 </body>
57 </html>